import {
  rolePageApi,
  addRoleApi,
  editRoleApi,
  delRoleApi,
  roleAllFuncApi,
  editRoleFuncApi
} from '@/api/system/role'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { treeForEach } from '@/utils/tree'
import { cloneDeep } from 'lodash-es'

type props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  drawerShow: Ref<boolean>
  roleForm: Ref<{ [index: string]: any }>
  proTableInst: Ref<ProTableInst | null>
  currentRole: Ref<any>
  roleFuncList: Ref<number[]>
  editFuncModal: Ref<boolean>
  funcTree: Ref<any[]>
}

export const useRoleApi = ({
  handleType,
  handleTag,
  drawerShow,
  roleForm,
  currentRole,
  roleFuncList,
  proTableInst,
  editFuncModal,
  funcTree
}: props) => {
  const confirmLoading = ref(false)
  const roleStatusLoading = ref(false)
  const editFuncModalLoading = ref(false)
  // 获取角色列表
  const fetchRolePage = async (pageRequest, queryParams) => {
    try {
      const res = await rolePageApi({
        ...queryParams,
        pageRequest
      })

      if (res.code === '0000') {
        return {
          data: res.data?.content,
          total: res.data?.total
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增修改角色请求
  const fetchAddOrEditRole = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addRoleApi : editRoleApi
    const data = { ...roleForm.value }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    if (res.code === '0000') {
      window['$message'].success(handleTag.value + '成功')
      proTableInst.value?.reload()
      drawerShow.value = false
    }
    confirmLoading.value = false
  }

  // 删除角色
  const fetchDelRole = async (id) => {
    try {
      const res = await delRoleApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 角色状态改变
  const changeRoleStatus = async (row) => {
    try {
      roleStatusLoading.value = true
      const res = await editRoleApi({
        ...row,
        validFlag: !row.validFlag
      })
      if (res.code === '0000') {
        window['$message'].success(`【${row.roleName}】角色状态改变成功`)
        proTableInst.value?.staticReload()
      }
    } catch (e) {
      console.log(e)
    } finally {
      roleStatusLoading.value = false
    }
  }

  // 获取所有权限
  const fetchRoleAllFunc = async () => {
    // editFuncModalLoading.value = true
    const res = await roleAllFuncApi({
      // roleCode: currentRole.value.roleCode
      isAllMenu: true
    })
    if (res.code === '0000') {
      funcTree.value = res.data
      // roleFuncList.value = handleRoleAllFuncData(res.data)
      // roleFuncList.value =
      //   currentRole.value.menuIds?.map((item) => parseInt(item)) || []
    }
    // editFuncModalLoading.value = false
  }

  // const handleRoleAllFuncData = (data = [], idList: number[] = []) => {
  //   data.forEach((item: any) => {
  //     if (item.id && item.isCheck && !item.children?.length) {
  //       idList.push(item.id)
  //     }

  //     if (item?.children?.length) {
  //       handleRoleAllFuncData(item.children, idList)
  //     } else {
  //       item.children = null
  //     }
  //   })
  //   return idList
  // }

  // 角色授权
  const fetchEditRoleFunc = async () => {
    editFuncModalLoading.value = true
    const res = await editRoleFuncApi({
      roleId: {
        id: currentRole.value.id
      },
      funcIds: getRoleFunc().map((key) => ({ id: key }))
    })

    if (res.code === '0000') {
      window['$message'].success('授权成功')
      editFuncModal.value = false
      proTableInst.value?.reload()
    }
    editFuncModalLoading.value = false
  }
  function getRoleFunc() {
    const data = cloneDeep(funcTree.value)
    const treeList: any[] = []
    treeForEach(data, (item) => {
      treeList.push(item)
    })
    const parentIdList: number[] = []
    roleFuncList.value.forEach((id) => {
      const role = treeList.find((item) => item.id === id)
      getParentId(role.id)
    })
    function getParentId(childId) {
      treeList.forEach((i) => {
        if (i.id === childId) {
          if (i.parentId !== 0) {
            parentIdList.push(i.parentId)
            getParentId(i.parentId)
          }
        }
      })
    }
    return [...new Set([...parentIdList, ...roleFuncList.value])]
  }

  return {
    fetchRolePage,
    fetchAddOrEditRole,
    fetchDelRole,
    changeRoleStatus,
    fetchRoleAllFunc,
    fetchEditRoleFunc,
    roleStatusLoading,
    editFuncModalLoading
  }
}
